package com.ping.shiro;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆过滤器，继承一个认证过滤器，来实现用户的登陆过滤
 * 
 * @author 浩子 2018年10月17日
 */
public class LoginFilter extends AuthenticationFilter {

	/**
	 * 返回true 则放行这个filter
	 */
	@Override
	protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String path = request.getServletPath();
		NotAuthorizationBean bean = new NotAuthorizationBean(path);
		if (ShiroUtil.isContains(bean)) {  //判断是否为
			// 不需要认证
			return true;
		}
		Subject subject = getSubject(servletRequest, servletResponse);
		if (subject.getPrincipals() != null) {
			return true;
		}
		return false;
	}

	/**
	 * 当isAccessAllowed，返回false时  执行这个方法
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
		ShiroUtil.writeResponse(new Result(AuthorizationStatus.NOT_LOGIN),(HttpServletResponse) servletResponse);
		return false;
	}

}
